package com.shiro.sdk.credentials;

import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.util.StringUtils;
import com.shiro.sdk.properties.JwtProperties;
import com.shiro.sdk.utils.JwtUtil;

/**
 * JWT证书匹配验证.
 * token 和 secret 必须都有值，否则返回 false 验证不通过
 */
public class JwtCredentialsMatcherOld implements CredentialsMatcher {

    private JwtProperties jwtProperties;

    public JwtCredentialsMatcherOld(JwtProperties jwtProperties){

        this.jwtProperties = jwtProperties;
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo){

        if((authenticationInfo instanceof SimpleAuthenticationInfo) == false){
            return false;
        }

        String token = authenticationToken.getCredentials().toString();
        if(!StringUtils.hasText(token)){
            return false;
        }
        String secret = authenticationInfo.getCredentials().toString();
        if(!StringUtils.hasText(secret)){
            return false;
        }

        String salt = new String(((SimpleAuthenticationInfo) authenticationInfo).getCredentialsSalt().getBytes());

        try {
            return new JwtUtil(jwtProperties).verify(token, secret, salt);
        } catch (Exception e) {
            throw e;
        }
    }
}
